package com.dlkj.threadPool.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dlkj.threadPool.core.encrypt.SecurityParameter;
import com.dlkj.threadPool.entity.Person;
import com.dlkj.threadPool.utils.Base64Utils;
import com.dlkj.threadPool.utils.EncryptUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Consts;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;

/**
 * @Author : lei
 * @Company ：DiLang Technology
 * @Date : 2019/1/12 10:20
 * @Description : 测试加解密controller
 **/
@RestController
public class EncryptController {

    @GetMapping("/get")
    @SecurityParameter
    public Person get() {
        return new Person("sam", "男");
    }

    @PostMapping("/save")
    @SecurityParameter
    public Person save(@RequestBody Person person) {
        System.out.println(person.getName());
        return person;
    }

    @PostMapping("upload")
    public JSONArray upload(StandardMultipartHttpServletRequest request) {
        File tempFile = null;
        JSONArray array = new JSONArray();
        String url = "http://smartcity.jiangmen.cn/upload";
        RestTemplate template = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>();
        MultipartFile file = request.getFile("file");
        try {
            String tempFilePath = System.getProperty("java.io.tmpdir") + file.getOriginalFilename();
            tempFile = new File(tempFilePath);
            file.transferTo(tempFile);
            FileSystemResource resource = new FileSystemResource(tempFilePath);
            parts.add("file", resource);
            Enumeration<String> enumeration = request.getParameterNames();
            while (enumeration.hasMoreElements()) {
                String key = enumeration.nextElement();
                parts.add(key, request.getParameter(key));
            }
            HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(parts, headers);
            String result = template.postForObject(url, httpEntity, String.class);
            array = JSONArray.parseArray(result);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (tempFile != null) {
                tempFile.delete();
            }
        }
        return array;
    }

    @PostMapping("httpUpload")
    public JSONArray httpUpload(@RequestParam("file") MultipartFile file) throws IOException {
        CloseableHttpClient client = HttpClientBuilder.create().build();
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(200000).setSocketTimeout(200000000).build();
        HttpPost post = new HttpPost("http://smartcity.jiangmen.cn/upload");
        post.setConfig(requestConfig);
        MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
        entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        entityBuilder.setContentType(ContentType.MULTIPART_FORM_DATA);
        String tempFilePath = System.getProperty("java.io.tmpdir") + file.getOriginalFilename();
        File tempFile = new File(tempFilePath);
        file.transferTo(tempFile);
        entityBuilder.addBinaryBody("file", tempFile, ContentType.MULTIPART_FORM_DATA, file.getOriginalFilename());
        post.setEntity(entityBuilder.build());
        CloseableHttpResponse response = client.execute(post);
        org.apache.http.HttpEntity entity = response.getEntity();
        int statusCode = response.getStatusLine().getStatusCode();
        StringBuffer buffer = new StringBuffer();
        if (statusCode == 200) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
            String str = "";
            while (StringUtils.isNotBlank(str = reader.readLine())) {
                buffer.append(str);
            }
        }
        client.close();
        if (response != null) {
            response.close();
        }
        if (tempFile != null) {
            tempFile.delete();
        }
        String result = buffer.toString();
        return JSONArray.parseArray(result);
    }

    @PostMapping("urlUpload")
    public JSONArray urlUpload(@RequestParam("urlPath") String urlPath) throws Exception {
        String tempFilePath = System.getProperty("java.io.tmpdir") + "1.jpg";
        File tempFile = new File(tempFilePath);
        if (naiveDownloadPicture(tempFile, urlPath)) {

        }
        return null;
    }

    @PostMapping("download")
    public boolean naiveDownloadPicture(@RequestParam("url") String url) {
        int i = url.lastIndexOf("/");
        String fileName = url.substring(i + 1);
        String tempFilePath = System.getProperty("java.io.tmpdir") + fileName;
        File file = new File(tempFilePath);
        return naiveDownloadPicture(file, url);
    }

    public boolean naiveDownloadPicture(File file, String urlstr) {
        URL url = null;
        HttpURLConnection httpConn = null;
        InputStream inputStream = null;
        FileOutputStream fileOutputStream = null;
        ByteArrayOutputStream bos = null;
        try {
            URL urlObj = new URL(urlstr);
            // 创建HttpURLConnection对象，通过这个对象打开跟远程服务器之间的连接
            httpConn = (HttpURLConnection) urlObj.openConnection();
            httpConn.setDoInput(true);
            httpConn.setRequestMethod("GET");
            httpConn.setConnectTimeout(5000);
            httpConn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            httpConn.connect();

            // 判断跟服务器的连接状态。如果是200，则说明连接正常，服务器有响应
            if (httpConn.getResponseCode() == 200) {
                // 服务器有响应后，会将访问的url页面中的内容放进inputStream中，使用httpConn就可以获取到这个字节流
                inputStream = httpConn.getInputStream();
                //为file生成对应的文件输出流
                fileOutputStream = new FileOutputStream(file);
                //定义字节数组大小
                byte[] buffer = new byte[1024];
                int len = 0;
                bos = new ByteArrayOutputStream();
                while ((len = inputStream.read(buffer)) != -1) {
                    bos.write(buffer, 0, len);
                }
                fileOutputStream.write(bos.toByteArray());
                return true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bos != null) {
                    bos.close();
                }
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    @PostMapping("stream")
    public String stream() {
        InputStream inputStream = null;
        FileOutputStream fileOutputStream = null;
        ByteArrayOutputStream bos = null;
        try {
            String url = "https://dev.gddlkj.com/IntelligentWuyiService/api/yqt/subsidy/images.do";
            CloseableHttpClient client = HttpClientBuilder.create().build();
            List<BasicNameValuePair> list = new ArrayList<>();
            list.add(new BasicNameValuePair("uuid", "52EFD9A4606E4579B1DF6039953BF121"));
            String params = EntityUtils.toString(new UrlEncodedFormEntity(list, Consts.UTF_8));
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(200000).setSocketTimeout(200000000).build();
            HttpGet get = new HttpGet (url+"?"+params);
            get.setConfig(requestConfig);
            CloseableHttpResponse response = client.execute(get);
            org.apache.http.HttpEntity entity = response.getEntity();
            inputStream = entity.getContent();
            byte[] buffer = new byte[1024];
            int len = 0;
            bos = new ByteArrayOutputStream();
            while ((len = inputStream.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }
            return Base64Utils.encode(bos.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        }  finally {
            try {
                if (bos != null) {
                    bos.close();
                }
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "";
    }


    @GetMapping("int")
    public String intPost() {
        try {
            String url = "https://bs-test.digitalgd.com.cn/ebus/usercenter/workitem/updateworkitem";

            String token = "bZgnUfoD361edto6pP8u14ZdnTrCvnyA";
            long timeMillis = System.currentTimeMillis();
            String timestamp = String.valueOf(timeMillis);
            timestamp = timestamp.substring(0,timestamp.length()-3);

            CloseableHttpClient client = HttpClientBuilder.create().build();
            List<BasicNameValuePair> list = new ArrayList<>();
            list.add(new BasicNameValuePair("row_guid", "0795c293-f70e-4b86-a91e-d268653fdb4b"));
            list.add(new BasicNameValuePair("state", "04"));
            list.add(new BasicNameValuePair("business_state", "已过期"));
            list.add(new BasicNameValuePair("cd_time", "1"));


            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8");
            entity.setContentType("application/json");
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(200000).setSocketTimeout(200000000).build();
            HttpPost post = new HttpPost (url);

            post.addHeader("x-tif-paasid", "gddlkj_yqt");
            post.addHeader("x-tif-signature", EncryptUtil.sha256(timestamp + token + "999" + timestamp));
            post.addHeader("x-tif-timestamp", timestamp);
            post.addHeader("x-tif-nonce", "999");

            post.setEntity(entity);
            post.setConfig(requestConfig);
            CloseableHttpResponse response = client.execute(post);
            return EntityUtils.toString(response.getEntity());
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }

    @GetMapping("json")
    public String jsonPost() {
        try {
            String url = "https://bs-test.digitalgd.com.cn/ebus/usercenter/workitem/updateworkitem";

            String token = "bZgnUfoD361edto6pP8u14ZdnTrCvnyA";
            long timeMillis = System.currentTimeMillis();
            String timestamp = String.valueOf(timeMillis);
            timestamp = timestamp.substring(0,timestamp.length()-3);

            CloseableHttpClient client = HttpClientBuilder.create().build();

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("row_guid", "e049c1f1-b1f3-44e8-9ac2-a9f749cfa0e1");
            jsonObject.put("state", "02");
            jsonObject.put("business_state", "办理中");
            jsonObject.put("cd_time", Integer.parseInt(timestamp));
            String jsonString = jsonObject.toJSONString();
            System.out.println(jsonString);
            StringEntity entity = new StringEntity(jsonString);
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");//发送json数据需要设置contentType
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(200000).setSocketTimeout(200000000).build();
            HttpPost post = new HttpPost (url);

            post.addHeader("x-tif-paasid", "gddlkj_yqt");
            post.addHeader("x-tif-signature", EncryptUtil.sha256(timestamp + token + "999" + timestamp));
            post.addHeader("x-tif-timestamp", timestamp);
            post.addHeader("x-tif-nonce", "999");

            post.setEntity(entity);
            post.setConfig(requestConfig);
            CloseableHttpResponse response = client.execute(post);
            return EntityUtils.toString(response.getEntity());
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        }
    }

    @GetMapping("rest")
    public String restPost() {
        String url = "https://bs-test.digitalgd.com.cn/ebus/usercenter/workitem/updateworkitem";

        String token = "bZgnUfoD361edto6pP8u14ZdnTrCvnyA";
        long timeMillis = System.currentTimeMillis();
        String timestamp = String.valueOf(timeMillis);
        timestamp = timestamp.substring(0,timestamp.length()-3);

        RestTemplate template = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>();

        parts.add("row_guid", "c45698e0-7cc6-43f4-83dd-2ccce78d3f2c");
        parts.add("state", "02");
        parts.add("business_state", "办理中");
        parts.add("cd_time", 1);

        headers.add("x-tif-paasid", "gddlkj_yqt");
        headers.add("x-tif-signature", EncryptUtil.sha256(timestamp + token + "999" + timestamp));
        headers.add("x-tif-timestamp", timestamp);
        headers.add("x-tif-nonce", "999");

        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(parts, headers);
        return template.postForObject(url, httpEntity, String.class);
    }
}
